"""
@Time : 2022/9/14 11:06
@Author : ls
@DES:
"""
import time
import platform
from ctypes import *
from config import settings
from models.custom_class import CoalYard


class AutoYard(object):

    def __init__(self, coal_yard: CoalYard, queue=None):
        self.queue = queue
        self.coal_yard = coal_yard
        self.radars = coal_yard.coalRadarList

        if platform.system() == 'Windows':
            from ctypes import windll
            dll_path = settings.STATIC_DIR + '/sdk/CDPSIMCLIENT-win64.dll'
            self.dll = windll.LoadLibrary(dll_path)
            self.CALLBACK = WINFUNCTYPE(None, c_uint, c_int, POINTER(c_char), c_int)
        else:
            from ctypes import cdll
            so_path = settings.STATIC_DIR + '/sdk/cdpsimclient-linux64.so'
            self.dll = cdll.LoadLibrary(so_path)
            self.CALLBACK = CFUNCTYPE(None, c_uint, c_int, POINTER(c_char), c_int)

    def get_queue(self):
        return self.queue

    def set_queue(self, queue):
        self.queue = queue

    def make_id(self):
        obj_id = id(self.coal_yard)
        str_id = str(obj_id)
        str_id = str_id[:-6]
        obj_id = int(str_id)
        return obj_id

    def sdk_init(self):
        print("执行初始化")
        self.dll.NET_SDK_SIMCLT_Init()

    def set_callback_function(self, func, addr_id):
        print("执行设置回调")
        call_back = self.CALLBACK(func)
        # gCallbackFuncList.append(call_back)
        self.dll.NET_SDK_SIMCLT_Set_Callback(call_back, addr_id)
        return call_back

    def radars_start_connect(self, wait_time: int):
        for radar in self.radars:
            cid = radar.id
            ip = bytes(radar.ip, encoding='utf-8')
            port = radar.port
            self.dll.NET_SDK_SIMCLT_StartConnect(cid, ip, port, 120)
        time.sleep(wait_time)

    def radar_stop(self, c_id):
        self.dll.NET_SDK_SIMCLT_ZTRD_RotateStop(c_id)
        self.dll.NET_SDK_SIMCLT_StopConnectCid(c_id)

    def radars_rotate_begin(self, run_mode, speed, angle_scan):
        sdk = self.dll
        for radar in self.radars:
            cid = radar.id
            sdk.NET_SDK_SIMCLT_ZTRD_RotateStop(cid)
            sdk.NET_SDK_SIMCLT_ZTRD_SetRunMode(cid, run_mode, 64, 0, 360)
            print(f'开始启动雷达， cid == {cid}')
            sdk.NET_SDK_SIMCLT_ZTRD_RotateBegin(cid, speed, 0, angle_scan)
